package com.weshare.nd.netty.server;

import com.weshare.nd.cmd.ChatCommand;
import com.weshare.nd.model.ChatMessage;
import com.weshare.nd.netty.contex.ChatContex;
import com.weshare.nd.util.GlobalConstant;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.Attribute;
import org.apache.log4j.Logger;

import java.util.Map;

public class ChatServerHandler extends SimpleChannelInboundHandler<Object> {

    private static final Logger logger = Logger.getLogger(ChatServerHandler.class);


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error("Unexpected exception from downstream.", cause);
        ctx.close();
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);

        logger.info("new client active.");

        Channel channel = ctx.channel();

        askLogin(channel);
    }

    public static String getRemoteAddress(ChannelHandlerContext ctx){
        String socketString = "";
        socketString = ctx.channel().remoteAddress().toString();
        return socketString;
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();

        Attribute<String> attr = channel.attr(GlobalConstant.CONTEX_KEY);

        String clientName = attr.get();

        //删除Channel Map中的失效Client
        ChatContex.removeChannel(clientName);

        ctx.close();

        logger.info("client [" + clientName + "] logout.");

    }


    @Override
    protected void messageReceived(ChannelHandlerContext channelHandlerContext, Object o) throws Exception {

        Channel thisChannel = channelHandlerContext.channel();

        ChatMessage chatMsg = (ChatMessage) o;

        if(chatMsg != null){
            ChatMessage repMsg = new ChatMessage();

            String command = chatMsg.getCommand();
            String clientName = chatMsg.getClientName();
            String msg = chatMsg.getMsg();

            Channel session = ChatContex.getChannel(clientName);

            if(session == null){
                if(ChatCommand.ANSWER.equals(command)){
                    ChatContex.addChannel(clientName, thisChannel);

                    Attribute<String> attr = thisChannel.attr(GlobalConstant.CONTEX_KEY);
                    attr.set(clientName);

                    repMsg.set(ChatCommand.PERSON_MAIL, clientName, "登录成功");

                    thisChannel.writeAndFlush(repMsg);

                }else{
                    askLogin(thisChannel);
                }
            }else {
                switch (command) {
                    case ChatCommand.ANSWER:

                        repMsg.set(ChatCommand.ASK, clientName, "用户名已存在，请重新输入：");

                        thisChannel.writeAndFlush(repMsg);

                        break;
                    case ChatCommand.NO_REPLY:

                        break;
                    case ChatCommand.TALK:
                        String talkMsg = "[" + clientName + "] : " + msg;

                        repMsg.set(ChatCommand.BROADCAST, clientName, talkMsg);

                        Map<String, Channel> sessionContex = ChatContex.getSessionContex();

                        for(Channel oneChannel : sessionContex.values()){
                            oneChannel.writeAndFlush(repMsg);
                        }
                        break;
                    default:
                        System.out.println("default");
                        break;
                }
            }

        }
        logger.info("SERVER接收到消息:" + o);
    }

    /**
     * 发送要求客户端登录信息
     * @param channel
     */
    public void askLogin(Channel channel){
        ChatMessage msg = new ChatMessage(ChatCommand.ASK, null, "请输入用户名：");

        channel.writeAndFlush(msg);
    }

}
